import { getLocalHistories } from '@/utils/storage';

// 初始化reducer
const initialState = {
  suggestList: [] as string[],
  // 保存搜索历史
  histories: getLocalHistories() as string[],
  // 保存搜索结果
  results: [] as ResultsType[],
};

export default function searchReducer(
  state = initialState,
  action: searchActionType
): typeof initialState {
  switch (action.type) {
    // 编写逻辑
    case 'search/saveList':
      return {
        ...state,
        // 筛选,处理后台没有数据时返回null的问题
        suggestList: action.payload.filter((item) => item),
      };
    // 2. 编写修改的逻辑
    case 'search/clearList':
      return {
        ...state,
        suggestList: [],
      };
    case 'search/saveHistories':
      // 💥 细节2：去重
      const newList = state.histories.filter((item) => item !== action.payload);
      return {
        ...state,
        // 3. 编写保存的逻辑
        histories: [action.payload, ...newList],
      };
    // 清除历史记录
    case 'search/clearHistories':
      return {
        ...state,
        histories: [],
      };
    // 保存搜索结果
    case 'search/saveResults':
      return {
        ...state,
        results: [...state.results, ...action.payload],
      };
    // 清除搜索结果
    case 'search/clearResults':
      return {
        ...state,
        results: [],
      };

    default:
      return state;
  }
}

// 定义action类型
export type searchActionType =
  | { type: 'search/saveList'; payload: string[] }
  // 1. 定义action的类型分支
  | { type: 'search/clearList' }
  // 保存搜索历史
  | { type: 'search/saveHistories'; payload: string }
  // 清除历史记录
  | { type: 'search/clearHistories' }
  // 保存搜索结果
  | { type: 'search/saveResults'; payload: ResultsType[] }
  // 清除搜索结果
  | { type: 'search/clearResults' };

export type ResultsType = {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: number;
  pubdate: string;
  cover: {
    type: number;
    images: string[];
  };
  like_count: number;
  collect_count: number;
};
